package com.blog.security.handler;

import com.alibaba.fastjson2.JSON;
import com.blog.common.CommonRespDto;
import com.blog.enums.ResponseCodeEnums;
import com.blog.security.entity.AuthUserDetails;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CustomAuthenticationFailureHandler
 * @Destription 自定义 处理“登录失败”的请求
 * @Author 天堂小野花
 * @Date 2025/8/10  16:38
 * @Version 1.0
 */
@Component
public class CustomAuthenticationFailureHandler implements ServerAuthenticationFailureHandler {
    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders headers = response.getHeaders();
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Cache-Control","no-store,no-cache,must-revalidate,max-age-8");
        //设置body
        CommonRespDto<AuthUserDetails> result = new CommonRespDto<>(ResponseCodeEnums.UNAUTHORIZED.getCode(),ResponseCodeEnums.UNAUTHORIZED.getMessage(),null);
        byte[] dataBytes = {};
        ObjectMapper mapper = new ObjectMapper();
        try {
            dataBytes = mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
}
